import { Select, Message } from 'antd';
import React, { useState, useEffect, useImperativeHandle } from 'react';
import { compare, compareClass } from 'src/utils/compare';
import TableEditor from 'src/components/TableEditor';
import PopValue from 'src/components/PopTab/PopValue';
import { cloneDeep } from 'lodash';
import { validateActions } from './validate';
import services from '../../services/api';
import { PARAMETER_TYPE } from '../../utils/constant';
import { VARIABLE_TYPE } from '../../utils/constant';
import useActionsData from 'src/hook/useActionsData';

export default function ActionsConfig(props) {
  const { actions } = props;
  const [value, setValue] = useState([]);
  const [riskTypes, setRiskTypes] = useState([]); // 风险类型
  const riskOptions = useActionsData();
  console.log(riskOptions);
  useImperativeHandle(props.createRef, () => ({
    // 暴露方法给父组件,收集验证值
    getValue: (cb) => {
      const isValidate = validate(value); // 验证数据
      if (isValidate) {
        cb(value, null);
      } else {
        cb(value, true);
      }
    },
  }));

  useEffect(() => {
    console.log(props, '动作节点');
    if (!props.riskTypes) {
      setRiskTypes(riskOptions);
    } else {
      setRiskTypes(props.riskTypes);
    }
  }, [props.riskTypes]);

  useEffect(() => {
    props.value && setValue(cloneDeep(props.value));
  }, [props.value]);

  // 验证数据
  function validate(value) {
    try {
      if (props.allowEmpyt && value.length === 0) {
        // 允许为空并且value为空时，不校验
        return value;
      } else {
        validateActions(value);
        return value;
      }
    } catch (error) {
      Message.warning(error);
      return false;
    }
  }

  function handelChange(value) {
    setValue(value);
    props.onChange && props.onChange(value);
  }

  function handleSelectParamChange(val, item, options, type) {
    if (options) {
      let name = '';
      if (type === 'interrupt') {
        name = val.map((item) => options.find((it) => it.code === item).name).join(',');
      } else {
        if (Array.isArray(val)) {
          name = val.map((item) => options.find((it) => it.code === item).value).join(',');
        } else {
          name = options.find((it) => it.code === val).value;
        }
      }
      item.value = { var_code: val, var_name: name, var_type: 'literal' };
    } else {
      // 系统函数不需要传name, 可以直接匹配code
      item.value = { var_code: val, var_type: 'literal' };
    }
    setValue(cloneDeep(value));
    props.onChange && props.onChange(value);
  }

  function handleDialogParamChange(val, item) {
    // 常量时没有匹配的name，只有code，把code赋值给name
    item.value = val
      ? {
          var_code: val.var_code,
          var_name: val.var_name || val.var_code,
          var_type: val.var_type,
          data_type: val.data_type,
        }
      : null;
    setValue(cloneDeep(value));
    props.onChange && props.onChange(value);
  }

  //handle code change
  const handleCodeChange = (val, index) => {
    if (val === 'interrupt' && value.some((item) => item.code === val)) {
      // 流程推出函数只允许存在一个
      return Message.warning('仅可添加一条流程退出动作');
    }
    const item = actions.find((it) => it.code === val);
    if (item) {
      value[index] = Object.assign({}, value[index], cloneDeep(item));
    }
    setValue(cloneDeep(value));
    // console.log(value)
    props.onChange && props.onChange(value);
  };

  // 系统内置函数
  const systemFunction = (record, index) => {
    let Com = '';
    switch (record.code) {
      // 流程退出
      case 'interrupt':
        Com = (
          <ProcessExit
            record={record}
            index={index}
            oldProps={props}
            riskTypes={riskTypes}
            handleSelectParamChange={handleSelectParamChange}
          />
        );
        break;
      // 字段赋值
      case 'field_assign':
        Com = (
          <VariableAssignment
            record={record}
            index={index}
            oldProps={props}
            handleDialogParamChange={handleDialogParamChange}
          />
        );
        break;
      // 案件生成
      case 'case_generate':
        // console.log(record);
        Com = <GeneratingCases />;
        break;
      default:
        break;
    }
    return Com;
  };
  const columns = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
      width: 60,
      render: (text, record, index) => {
        return <>{index + 1}</>;
      },
    },
    {
      dataIndex: 'code',
      key: 'code',
      width: 150,
      title: '动作类型',
      render: (text, record, index) => {
        return (
          <>
            <Select
              style={{ width: '120px', ...compare(props, index, 'code') }}
              onChange={(value) => handleCodeChange(value, index)}
              value={record.code}
              disabled={props.disabled}
            >
              {actions.map((it) => (
                <Select.Option value={it.code} key={it.code}>
                  {it.name}
                </Select.Option>
              ))}
            </Select>
          </>
        );
      },
    },
    {
      dataIndex: 'parameters',
      key: 'parameters',
      title: '函数表达式',
      render: (text, record, index) => {
        return (
          <div className='flex' style={{ flexWrap: 'wrap' }}>
            {systemFunction(record, index) ||
              (record.parameters &&
                record.parameters.map((item, i) => {
                  return (
                    <div className='flex' key={i} style={i !== 0 ? { marginTop: 5 } : null}>
                      {item.isNull === 0 && <span style={{ color: 'red', marginRight: 5 }}>*</span>}
                      {item.name && (
                        <span
                          style={{
                            marginRight: '10px',
                          }}
                        >
                          {item.name}:
                        </span>
                      )}
                      {item.showType === PARAMETER_TYPE._SINGLE && (
                        <Select
                          onChange={(value) => handleSelectParamChange(value, item, item.options)}
                          placeholder='请选择'
                          style={{
                            width: '120px',
                            marginRight: '10px',
                            ...compare(props, index, 'parameters', i, 'value', 'var_code'),
                          }}
                          value={item.value && (props.isImportant ? item.value.var_name : item.value.var_code)}
                          disabled={props.disabled}
                        >
                          {item.options.map((it) => (
                            <Select.Option value={it.code} key={it.code}>
                              {it.value}
                            </Select.Option>
                          ))}
                        </Select>
                      )}
                      {item.showType === PARAMETER_TYPE._MULTIPLE && (
                        <Select
                          onChange={(value) => handleSelectParamChange(value, item, item.options)}
                          mode='multiple'
                          placeholder='请选择'
                          style={{
                            width: '120px',
                            marginRight: '10px',
                          }}
                          className={compare(props, index, 'parameters', i, 'value', 'var_code')}
                          value={
                            item.value &&
                            (props.isImportant
                              ? item.value.var_name
                              : item.value.var_code &&
                                (Array.isArray(item.value.var_code)
                                  ? item.value.var_code
                                  : item.value.var_code.split(',')))
                          }
                          disabled={props.disabled}
                          showArrow={true}
                        >
                          {item.options.map((it) => (
                            <Select.Option value={it.code} key={it.code}>
                              {it.value}
                            </Select.Option>
                          ))}
                        </Select>
                      )}
                      {item.showType === PARAMETER_TYPE._INPUT && (
                        <PopValue
                          {...props}
                          limitType={item.varTypeLimit}
                          variable={props.variable}
                          using_variables={props.using_variables}
                          value={item.value}
                          disabled={props.disabled}
                          onChange={(value) => handleDialogParamChange(value, item)}
                          style={{
                            width: '120px',
                            marginRight: 10,
                            ...compare(props, index, 'parameters', i, 'value', 'var_code'),
                          }}
                        />
                      )}
                      {i === 0 && record.symbol && <div style={{ margin: '0 10px' }}>{record.symbol}</div>}
                    </div>
                  );
                }))}
          </div>
        );
      },
    },
  ];

  return (
    <div>
      <TableEditor
        columns={columns}
        initItem={{
          code: '',
          name: '',
          parameters: [],
          symbol: '',
        }}
        dataSource={value}
        onChange={handelChange}
        noNeedAdd={props.disabled}
        disabled={props.disabled}
        operaterWidth={140}
        getButtonGroup={({ moveUpButton, moveDownButton, removeButton }) => {
          return [moveUpButton, moveDownButton, removeButton];
        }}
      />
    </div>
  );
}

// 系统内置函数 流程退出
function ProcessExit(props) {
  const { record, index, oldProps, riskTypes, handleSelectParamChange } = props;
  const { parameters } = record;
  // console.log('parameters：')
  // console.log(parameters)

  const selectChange = (value) => {
    handleSelectParamChange(value, parameters[0]);
    if (value === 'pass') handleSelectParamChange(null, parameters[1]);
  };

  const multipleSelectChange = (value) => {
    if (value && value.length > 5) return;
    handleSelectParamChange(value, parameters[1], riskTypes, 'interrupt');
  };
  return (
    <>
      {/* 风控结果 */}
      <div className='flex'>
        {parameters[0].isNull === 0 && <span style={{ color: 'red', marginRight: 5 }}>*</span>}
        <span style={{ marginRight: '10px' }}>{parameters[0].name}</span>

        <Select
          onChange={(value) => selectChange(value)}
          placeholder='请选择'
          style={{
            width: '120px',
            marginRight: '10px',
            ...compare(oldProps, index, 'parameters', 0, 'value', 'var_code'),
          }}
          value={parameters[0].value && parameters[0].value.var_code}
          disabled={oldProps.disabled}
        >
          {parameters[0].options.map((it) => (
            <Select.Option value={it.code} key={it.code}>
              {it.value}
            </Select.Option>
          ))}
        </Select>
      </div>
      {/* 风险类型 */}
      {parameters[0].value && parameters[0].value.var_code !== 'pass' && (
        <div className='flex'>
          <span style={{ color: 'red', marginRight: 5 }}>*</span>
          <span style={{ marginRight: '10px' }}>{parameters[1].name}</span>

          <Select
            onChange={(value) => multipleSelectChange(value)}
            mode='multiple'
            placeholder='请选择'
            style={{
              width: '120px',
              marginRight: '10px',
            }}
            className={compareClass(oldProps, index, 'parameters', 1, 'value', 'var_code')}
            value={(parameters[1].value && parameters[1].value.var_code) || []}
            disabled={oldProps.disabled}
          >
            {riskTypes.map((it) => (
              <Select.Option value={it.code} key={it.code}>
                {it.name}
              </Select.Option>
            ))}
          </Select>
        </div>
      )}
    </>
  );
}

// 系统内置函数 字段赋值
function VariableAssignment(props) {
  const { record, index, oldProps, handleDialogParamChange } = props;
  const { parameters } = record;
  // console.log(parameters);

  const lastSelectChange = (value) => {
    handleDialogParamChange(value, parameters[0]);
    handleDialogParamChange(null, parameters[1]);
  };

  const nextSelectChange = (value, type) => {
    handleDialogParamChange(value, parameters[1]);
  };
  // console.log('字段赋值', props)
  return (
    <>
      <div className='flex'>
        {parameters[0].isNull === 0 && <span style={{ color: 'red', marginRight: 5 }}>*</span>}
        <PopValue
          {...oldProps}
          limitType={parameters[0].varTypeLimit}
          variable={oldProps.variable}
          using_variables={oldProps.using_variables}
          value={parameters[0].value}
          disabled={oldProps.disabled}
          onChange={(value) => lastSelectChange(value)}
          style={{ width: '120px', ...compare(oldProps, index, 'parameters', 0, 'value', 'var_code') }}
          fieldClass={2}
          isLeft={true}
        />
        <div style={{ margin: '0 10px' }}>{record.symbol}</div>
        {parameters[1].isNull === 0 && <span style={{ color: 'red', marginRight: 5 }}>*</span>}
        <PopValue
          {...oldProps}
          limitType={parameters[1].varTypeLimit}
          dataType={parameters[0].value && [parameters[0].value.data_type]}
          variable={oldProps.variable}
          using_variables={oldProps.using_variables}
          value={parameters[1].value}
          disabled={oldProps.disabled}
          onChange={(value, type) => nextSelectChange(value, type)}
          style={{ width: '120px', ...compare(oldProps, index, 'parameters', 1, 'value', 'var_code') }}
          type={(parameters[1].value && parameters[1].value.var_type) || VARIABLE_TYPE._LITERAL} // tab默认常量
          leftVar={parameters[0].value && { code: parameters[0].value.var_code, type: parameters[0].value.var_type }}
        />
      </div>
    </>
  );
}

// 系统内置函数 生成案件
function GeneratingCases(props) {
  return (
    <>
      <div className='flex'>
        <span>生成核查案件</span>
      </div>
    </>
  );
}
